package com.sxs.app.service;

import com.sxs.app.dao.AppCategoryDao;
import com.sxs.app.entity.AppCategory;
import com.sxs.app.vo.TreeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryService {
    @Autowired
    AppCategoryDao appCategoryDao;

    public TreeVo getTree() {
        TreeVo tree = new TreeVo();

        List<TreeVo> vos = new ArrayList<>();
        List<AppCategory> list = appCategoryDao.queryAllBy(new AppCategory());
        for (AppCategory appCategory : list) {
            TreeVo vo = new TreeVo();
            BeanUtils.copyProperties(appCategory,vo);
            vos.add(vo);
        }

        //递归查询找子孙后代

        for (TreeVo vo : vos) {
            if(vo.getParentid()==null){
                tree =findChildren(vo,vos);
            }
        }
        return tree;
    }

    private TreeVo findChildren(TreeVo vo,List<TreeVo> vos){
        vo.setChildren(new ArrayList<>());

        for (TreeVo treeVo : vos) {
            if(vo.getId()==treeVo.getParentid()){
                vo.getChildren().add(treeVo);
                findChildren(treeVo,vos);
            }
        }
        return vo;
    }
}
